const fs = require('fs');
const path = require('path');
// 第一步，导入必要的模块
const archiver = require('archiver');
const { execSync } = require('child_process');

const appsDir = path.join(__dirname, '../project'); // 上级目录
console.log(appsDir)
const apps = fs.readdirSync(appsDir).filter(name => {
  const dir = path.join(appsDir, name);
  return fs.statSync(dir).isDirectory();
});
console.log('全部文件列表：', apps)

// 获取所有应用包名称
// const giteeUrl = 'https://gitee.com/YOUR_USERNAME/YOUR_REPO.git';

let newapps = apps.filter(item => {
  return item !== 'serve'
})
newapps.forEach(name => {
  // const appPath = path.join(appsDir, name);
  const appPath = path.join(appsDir, `${name}/源码包`);
  console.log(appPath)
  // 源码包package.json文件
  const packageJsonPath = path.join(appPath, 'package.json');
  // 要压缩文件
  const compressedPath = path.join(appsDir, `${name}/发布包`);
  // 压缩文件路径
  const compressedFilePath = path.join(compressedPath, 'dist');
  console.log(packageJsonPath)


  // 判断是否有pnpm或yarn依赖
  const packageJson = fs.readFileSync(packageJsonPath);
  console.log(packageJson)
  if (packageJson.indexOf('npm') > -1) {
    console.log(`[${name}] 下载依赖  打包中... use npm`);
    execSync(`cd ${appPath} && npm install && npm run build`);
    console.log(`[${name}] 打包完成... build end`);
  } else if (packageJson.indexOf('yarn') > -1) {
    console.log(`[${name}] 下载依赖 打包中... use yarn`);
    // execSync(`cd ${appPath} npm install -g`);
    execSync(`cd ${appPath} && yarn install  && yarn build`);
    console.log(`[${name}] 打包完成... build end`);
  } else {
    // execSync(`cd ${appPath} && npm install -g pnpm`);
    console.log(`[${name}] 下载依赖 打包中... use pnpm`);
    execSync(`cd ${appPath} && pnpm install && pnpm run build`);
    console.log(`[${name}] 打包完成... build end`);
  }

  // 压缩zip包
  console.log(`正在压缩开始：${name}...`);
  // 第二步，创建可写流来写入数据
  const output = fs.createWriteStream(path.join(compressedPath, `${name}.zip`));
  const archive = archiver('zip', {
    zlib: { level: 9 }, // 设置压缩级别
  });
  // 第三步，建立管道连接
  archive.pipe(output);
  // 第四步，压缩指定文件
  archive.directory(path.join(compressedFilePath), false);
  // 第五步，完成压缩
  archive.finalize();
  console.log(`全部压缩完成`);



  // 删除dist文件夹
  //  rimraf.sync(path.join(compressedFilePath, 'dist'));
  // 删除node_modules文件夹
  //  rimraf.sync(path.join(appPath, 'node_modules'));



  // 执行打包命令
  // console.log(`[${name}] 打包开始 build start`);
  // execSync(`cd ${appPath} && pnpm run build`);
  // console.log(`[${name}] 打包完成 build end`);



  // 将打包结果上传到gitee
  // console.log(`[${name}] deploy start`);
  // execSync(`cd ${appPath}/build && git init && git remote add origin ${giteeUrl} && git add . && git commit -m "deploy" && git push -f origin master`);
  // console.log(`[${name}] deploy end`);
});



